<template>
  <div class="tracetask-container">
    <v-layout wrap justify-space-between align-center>
      <v-flex md8 style="height: 15rem;" pl-3>
        <v-carousel show-arrows hide-delimiters height="15rem">
          <v-carousel-item v-for="(item, i) in carouselItems" :key="i" >
            <a :href="item.url">
              <img class="carousel-image cursor" :src="item.img" alt="">
            </a>
          </v-carousel-item>
        </v-carousel>
      </v-flex>
      <v-flex md4> 
        <a :href="sideImage.url">
          <img  style="max-height:100%;max-width:100%;"  :src="sideImage.img" alt="" >
        </a>
      </v-flex>
      <v-flex md12 mt-4>
        <h2 style="text-align: left;">{{ $category.text }}</h2>
        <v-layout class="list" justify-start align-start wrap>
          <v-flex
            px-2
            class="card item cursor"
            v-for="(item, i) of missionList"
            @click="onMissionDetail(item)"
          >
            <ui-mission :mission="item" />
          </v-flex>
        </v-layout>
      </v-flex>
      <v-flex md12 v-if="missionList.length > 0">
        <v-pagination
          @input="onPageChange"
          :length="pagination.pageCount"
          circle
          total-visible="5"
          v-model="pagination.page"
        ></v-pagination>
      </v-flex>
    </v-layout>
  </div>
</template>


<script lang="ts">
// 使用类装饰器
import { Component, Vue } from "vue-property-decorator";
import { Api } from "@/api";
import { forEach } from "lodash";
import { KV } from "@/utils/type";
import { PageOptions, TopupStatusKV } from "@/utils/constants";
import { ReqProfitIncome, ReqTaskInfo } from "@/api/bean";
import { getTime } from "@/utils/commonUtils";
import Cookie from 'js-cookie';
import { State, Action, Mutation, Getter, namespace } from "vuex-class";
const varsModule = namespace('varsModule');
const userModule = namespace('userModule');
declare const $Vue: Vue;

@Component
export default class Missions extends Vue {

  @varsModule.State('$category') $category: any;
  @userModule.Action('logoutFN') logoutFN: any;

  private carouselItems: any = [{

  }]

  private sideImage: any = {
    img: require('@/assets/images/ban1.png'),
    url: '',
  }

  private categories: Array<KV> = [
    { text: "", value: '' },
    { text: "Prime Video", value: 1 },
    { text: "Music, CDs & Vinyl", value: 2 },
    { text: "Digital Music", value: 3 },
    { text: "Kindle Store", value: 4 },
    { text: "Arts & Crafts", value: 5 },
    { text: "Automotive", value: 6 },
    { text: "Baby", value: 7 },
    { text: "Beauty & Personal Care", value: 8 },
    { text: "Books", value: 9 },
    { text: "Computers", value: 10 },
    { text: "Electronics", value: 11 },
    { text: "Women's Fashion", value: 12 },
    { text: "Men's Fashion", value: 13 },
    { text: "Girls' Fashion", value: 14 },
    { text: "Boys' Fashion", value: 15 },
    { text: "Health & Household", value: 16 },
    { text: "Home & Kitchen", value: 17 },
    { text: "Industrial & Scientific", value: 18 },
    { text: "Luggage", value: 19 },
    { text: "Movies & Television", value: 20 },
    { text: "Pet Supplies", value: 21 },
    { text: "Software", value: 22 },
    { text: "Sports & Outdoors", value: 23 },
    { text: "Tools & Home Improvement", value: 24 },
    { text: "Toys & Games", value: 25 },
    { text: "Video Games", value: 26 }
  ];

  private websites: Array<KV> = [
    { text: "", value: '' },
    { text: "USA", value: 1 },
    { text: "France", value: 2 }
  ];

  private pageOptions: any = [];
  private buyerStatus: any = TopupStatusKV;

  private queryForm: any = {
    website: "",
    category: "",
  };

  private headers: Array<any> = [];

  private missionList: any = [
  ];

  private loading: boolean = false;
  private dialog: boolean = false;
  private dialogItem: any = {};
  private isQuery: boolean = false;

  private pagination: any = {
    pageCount: 1,
    page: 1,
    limit: 25,
    offset: 0
  };

  private getTime(date: string) {
    return getTime(date);
  }

  protected mounted() {

    this.getMissionList();
    this.getSlideshowList();

    if (!Cookie.get('p_token')) {
      this.logoutFN();
    }

    // $Vue.$emit("balance");

    // $Vue.$emit("title", { message: 'Missions' });
    this.pageOptions = PageOptions.slice();
    $Vue.$once('refresh', ()=>{
      this.clearPage();
      this.getMissionList();
    });
    $Vue.$off('Missions');
    $Vue.$on('Missions', ()=>{
      this.clearPage();
      this.getMissionList();
    });

    $Vue.$off('SearchMission');
    $Vue.$on('SearchMission', (data: any)=>{
      this.clearPage();
      this.getMissionList(data);
    });

    let query = this.$route.query.type;
    if (query === 'search') {
      this.getMissionList(this.$route.params);
    }
  }

  private onPageOptionChange(value: any) {
    this.pagination.page = 1;
    this.pagination.offset = 0;
  }

  private clearPage() {
    this.pagination.page = 1;
    this.pagination.offset = 0;
  }

  private onClear() {
    this.queryForm = {
      website: '',
      category: '',
    }
  }

  private onSearch(from?: string) {
    let params: any = {};

    let valid = 0;
    forEach(this.queryForm, (item, key) => {
      item ? (params[key] = item) : valid++;
    });

    if (from === undefined) {
      this.pagination.offset = 0;
      this.pagination.page = 1;
    }

    params.limit = this.pagination.limit;
    params.offset = this.pagination.offset;
    this.isQuery = true;
    this.getMissionList(params);
  }

  private onJoinMissionClicked(item: any) {
    this.joinMission(item);
  }

  private onMissionDetail(data: any) {
    sessionStorage.setItem("MissionDetail", JSON.stringify(data));
    this.$router.push({
      name: "MissionDetail",
      params: data
    });
  }

  private onPageChange(value: any) {
    let limit = this.pagination.limit;
    this.pagination.offset = (value - 1) * limit;
    if (!this.isQuery) {
      this.getMissionList();
    } else {
      this.onSearch("wyvonj");
    }
  }

  private async getMissionList(add?: any) {
    if (!add) {
      add = {};
    }

    const params: ReqTaskInfo = {
      offset: this.pagination.offset,
      limit: this.pagination.limit,
      ...add,
      publishStatus: 1,
    };
    if (this.$category.value !== -1) {
      params.category = this.$category.value;
    }
    const { data } = await Api.getTaskList.r(params);
    console.log("getTaskList", data);
    if (data.result === 0) {
      let $data = data.data;
      // 设置总数
      // this.pagination.pageCount = data.data.totalCount;
      // this.pagination.offset += data.data.dataList.length;
      let userId: any = Cookie.get('p_userId');
      $data.dataList.forEach((item: any) => {
        if (item.buyerUserIds !== null) {
          let userIds: Array<string> = item.buyerUserIds.split(",");
          if (userIds.indexOf(userId) === -1) {
            item.showButton = true;
          }
        } else {
          item.showButton = true;
        }
      });

      this.missionList = $data.dataList;
      this.pagination.pageCount = $data.totalCount
        ? Math.ceil($data.totalCount / this.pagination.limit)
        : 1;
    } else {

    }
  }

  /**
   * 任务抢单 抢单之后可以通过上传 订单和评价截图 用于完成任务
   */
  private async joinMission(task: any) {
    const params = {
      taskId: task.taskId
    };
    const { data } = await Api.competeOrder.r(params);
    console.log("getTaskList", data);
    if (data.result === 0) {
      task.scalped = true;
      $Vue.$emit("snackbar", {
        text: data.message,
      });
    } else {
      $Vue.$emit("snackbar", {
        text: data.message,
      });
    }
  }

  /**
   * 获取首页轮播图
   */
  private async getSlideshowList() {
    const params = {
      offset: 0,
      limit: 1000,
    };
    const { data } = await Api.getSlideshowList.r(params);
    console.log("getSlideshowList", data);
    if (data.result === 0) {
      if (data.data.dataList.length > 0) {
        let cList: any = [];
        data.data.dataList.forEach((item) => {
          if (item.type === 1) {
            cList.push(item)
          }
          if (item.type === 2) {
            this.sideImage = item;
          }
        })
        this.carouselItems = cList;
      }
    } else {
      $Vue.$emit("snackbar", {
        text: data.message,
      });
    }
  }

}
</script>

<style lang="less" scoped>
.tracetask-container {
  width: 100%;
  height: 100%;
}
.pagination-wrapper {
  background: white;
  border-top: 1px solid #d4d4d4;
}
.list {
  padding-top: 0.3rem;
  width: 100%;
  height: 100%;
  padding: 0;
  list-style-type: none;
  text-align: center;
  position: relative;
  .item {
    background-color: white;
    margin-bottom: 0.4rem;
    width: 100%;
    display: flex;
    padding: 6px 0;
    text-align: left;
    justify-content: space-between;
    box-sizing: border-box;
    height: 20rem;
    border-radius: 12px;
    width: 19%;
    max-width: 19%;
    flex-basis: 19%;
    margin-right: 1%;
  }
}
.carousel-image {
  width: 100%;
  height: 100%;
}
</style>


